Data Structure--Priority Queue
- Collection : Insert and delete items.
But Which item to delete?
-
Stack. Remove the item most recently added
-
Queue. Remove the imte least recently added
-
Randomized queue. Remove a random item
-
Priority queue. Remove the largest (or smallest) item.
APIs:
public class MaxPQ<Key extends Comparable <Key>>
Challenge. Find the lagest M items in a stream of N items
优先队列的无序数组实现形式
最后我们可以写出整个PQ类的程序:
Heapsort
最后介绍基于binary heap的heapsort: basic plan:
- 先把二叉树变成heapsort,即父节点大于子节点
- repeatly delete the max key
代码入下:
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768import static java.lang.System.out;/*** Implements a <i>Heapsort</i>.** <h5>Lecture: Heapsort (Week 4)</h5>** <p>* Worst case this algorithms works in 2 N lg N running time.* Best case works in N lg N running time.* </p>** <p>* Faster than Selection, Insertion, Shell, Quick and 3-way quick.* But slow than Mergesort.* </p>** @author eder.magalhaes*/public class Heap {private static void sink (Comparable[] pq, int k, int N) {while (2 * k <= N) {int j = 2 * k;if (j < N && less(pq, j, j+1))j++;if (!less(pq, k, j))break;exch(pq, k, j);k = j;}}private static void exch(Object[] pq, int i, int j) {Object swap = pq[i-1];pq[i-1] = pq[j-1];pq[j-1] = swap;}private static boolean less(Comparable[] pq, int i, int j) {return pq[i-1].compareTo(pq[j-1]) < 0;}public static void sort(Comparable[] pq) {int N = pq.length;for (int k = N/2; k >= 1; k--) //此处从数组最后一个父节点,即最后一个节点 // 的父节点开始,遍历节点,使得整个数组为heap-sortedsink(pq, k, N);while (N > 1) {exch(pq, 1, N--);//把最大的放到末尾,把N-1的元素放到树顶去sinksink(pq, 1, N);//重复做}}public static void main(String[] args) {Integer[] data = new Integer[] {95, 29, 57, 82, 41, 83, 52, 21, 94, 79};sort(data);out.print("Array sorted by Heapsort: ");for (Integer x: data) {out.printf("%s ",x);}}}
复杂度比较
Significance. In-place sorting algorithm with** N log N worst-case.**
Mergesort: no, linear extra space. Quicksort : no, quadratic time in worst case. Heapsort: yes!
Bottom line. Heapsort is optimal for both time and space, but: Inner loop longer than quicksort’s. Makes poor use of cache memory. Not stable.